<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/4
 * Time: 10:43
 */

namespace app\alliance\controller;

use app\service\IGeTuiService;
use app\service\MemberService;
use app\service\RedPacketService;
use app\service\TaskService;
use Redis\Redis;
use think\Db;

class PlayerRedPacket extends Common
{
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 发红包
     */
    function sendRedEnvelopes()
    {
        # 接收红包类型  1=>金币  2=>积分
        $type = input('post.type');
        # 接收红包总数量/金额
        $money = input('post.money');
        # 接收红包个数
        $num = input('post.num');
        # 接收发送红包的人群 1=>团队玩家  2=>我的直推  3=>我的隔代  4=>其他玩家
        $people = input('post.people');
        # 红包标题
        $title = input('post.title');
        if (empty($title)) {
            $title = '恭喜发财';
        }
        # 操作密码
        $pwd = input('post.pwd');
        if (!empty($type) and !empty($money) and !empty($num) and !empty($people) and !empty($pwd)) {
            # 判断操作密码是否正确
            if (md5($pwd) != $this->memberInfo['operate_pwd']) {
                return array('status' => false, 'msg' => '操作密码不正确');
            }
            # 判断余额是否足够
            # 扣除金币/积分
            if ($type == 1) {
                if ($this->memberInfo['gold'] < $money) {
                    return array('status' => false, 'msg' => '金币余额不足');
                }
            } else {
                if ($this->memberInfo['integral'] < $money) {
                    return array('status' => false, 'msg' => '积分余额不足');
                }
            }
            # 添加发送包信息
            $redPacketId = Db::table('redpacket')->insertGetId(array(
                'member_code' => $this->code,
                'pack_type' => $type,
                'pack_value' => $money,
                'pack_num' => $num,
                'receipt_crowd' => $people,
                'pack_title' => $title,
                'plurs_num' => $num
            ));
            $redis = new Redis();
            # 将红包信息存入redis
            $redInfo = array(
                'name' => $this->memberInfo['name'],
                'head' => imgUrl($this->memberInfo['head_portrait']),
                'title' => $title,
                'redPacketId' => $redPacketId,
                'type' => $type
            );
            $redis->hSetJson('sendRedPacketInfo', strval($redPacketId), $redInfo);
            if (!$redPacketId) {
                return array('status' => false, 'msg' => '发送红包信息添加失败');
            }
            if ($type == 1) {
                # 扣金币
                Db::table('member_property')->where(array('member_code' => $this->code))->setDec('gold', $money);
                # 金币记录
                MemberService::addLog_gold($this->code, $money, 16, $redPacketId);
                # 更新用户redis
                $this->memberInfo['gold'] = priceFormat($this->memberInfo['gold'] - $money);
            } else {
                # 扣积分
                Db::table('member_property')->where(array('member_code' => $this->code))->setDec('integral', $money);
                # 积分记录
                MemberService::addLog_integral($this->code, $money, 2, 11, $redPacketId);
                # 更新用户redis
                $this->memberInfo['integral'] = priceFormat($this->memberInfo['integral'] - $money);
            }
            # 更新用户redis
            $redis->hSetJson('memberInfo', $this->code, $this->memberInfo);
            # 查询人群
            $peopleReturn = MemberService::relationship($this->code, $this->memberInfo['team_id'], $people);
            if ($peopleReturn['status'] == false) {
                return array('status' => false, 'msg' => '接收人群为空');
            }
            $peopleInfo = $peopleReturn['peopleInfo'];
            # 能领取红包的人存入redis
            $getui = new IGeTuiService();
            foreach ($peopleInfo as $k => $v) {
                RedPacketService::addMemberRedPacket($v, array('redpacket_id' => $redPacketId, 'expiration' => date('Y-m-d H:i:s', strtotime('+ 2 hours'))));
                $getui->pushMessageToSingle('', '红包来了', $title, $v, 2);
            }
            # 红包拆分,存入redis
            RedPacketService::redPacketList($redPacketId, $num, $money);
            # 存储红包接收人的关系
            RedPacketService::setRedPacketMemberMapping($redPacketId, $peopleInfo);
            # 设置红包领取关系过期时间，用户红包过期时间
            RedPacketService::setExperition($redPacketId);
            # 完成任务=>发红包
            TaskService::finishTask($this->code, 6);
            return array('status' => true, 'msg' => '发送成功');
        } else {
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询红包接收人群
     */
    function getPeopleInfo()
    {
        # 接收发送红包的人群 1=>团队玩家  2=>我的直推  3=>我的隔代  4=>其他玩家
        $people = input('post.people');
        $peopleReturn = MemberService::relationship($this->code, $this->memberInfo['team_id'], $people);
        return $peopleReturn;
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 抢红包
     */
    function GrabRedEnvelope()
    {
        # 红包ID
        $redpacketId = input('post.redpacket_id');
        # 类型  1->金币  2->积分
        $type = input('post.type');
        if (!empty($redpacketId) and !empty($type)) {
//            $redpacketId = $redpacketInfo['data']['redPacketId'];
            $redis = new Redis();
            # 获取红包列表
            $redPacketList = $redis->lRanges("redpack_detail" . $redpacketId, 0, -1);
            if (empty($redPacketList)) {
                return array('status' => false, 'msg' => '红包被抢完了');
            }
            # 判断是否领取过该红包
            $logRedPacket = Db::table('log_redpacket')->where(array('packet_id' => $redpacketId, 'member_code' => $this->code))->find();
            if (!empty($logRedPacket)) {
                return array('status' => false, 'msg' => '该红包已经被领取过了');
            }
            # 确定领取的红包金额
            $money = $redis->lPop('redpack_detail' . $redpacketId);# lPop() 移除并返回列表的第一个元素
            if (!empty($money)) {
                # 增加金币/积分
                if ($type == 1) {
                    # 金币
                    Db::table('member_property')->where(array('member_code' => $this->code))->setInc('gold', $money);
                    Db::table('member_property')->where(array('member_code' => $this->code))->setInc('gold', $money);
                    # 金币记录
                    MemberService::addLog_gold($this->code, $money, 17, $redpacketId);
//                    MemberService::addLog_income($this->code, $money, 4, 11);
                    # 更新用户redis
                    $this->memberInfo['gold'] = priceFormat($this->memberInfo['gold'] + $money);
//                    $this->memberInfo['income'] = priceFormat($this->memberInfo['income'] + $money);
                } else {
                    # 积分
                    Db::table('member_property')->where(array('member_code' => $this->code))->setInc('integral', $money);
                    # 积分记录
                    MemberService::addLog_integral($this->code, $money, 1, 12, $redpacketId);
                    # 更新用户redis
                    $this->memberInfo['integral'] = priceFormat($this->memberInfo['integral'] + $money);
                }
                # 更新用户redis
                $redis->hSetJson('memberInfo', $this->code, $this->memberInfo);
                # 添加红包领取记录
                Db::table('log_redpacket')->insert(array(
                    'packet_id' => $redpacketId,
                    'member_code' => $this->code,
                    'create_time' => date("Y-m-d H:i:s"),
                    'price' => priceFormat($money)
                ));
                # 修改红包剩余数量
                Db::table('redpacket')->where(array('id' => $redpacketId))->setDec('plurs_num', 1);
                # 已领取,  移除redis
                $redis->hDel("redpack_member" . $this->code, $redpacketId);
                # 更新用户关系
                $group = RedPacketService::getRedPacketMemberMapping($redpacketId);
                unset($group[$this->code]);
                RedPacketService::setRedPacketMemberMapping($redpacketId, $group);
                return array('status' => true, 'msg' => '领取成功', 'money' => $money, 'type' => $type);
            } else {
                return array('status' => false, 'msg' => '红包被抢光了');
            }
        } else {
            return array('status' => false, 'msg' => '没有可以领取的红包');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 红包领取记录
     */
    function logRedPacket()
    {
        $redpacketId = input('post.redpacket_id');
        if (!empty($redpacketId)) {
            # 查询红包领取记录
            $logInfo = Db::table('log_redpacket lr')
                ->field('name,head_portrait,price,date_format(lr.create_time,"%H:%i") time')
                ->leftJoin('member m', 'lr.member_code=m.code')
                ->where(array('packet_id' => $redpacketId))
                ->order('lr.id desc')
                ->select();
            if (!empty($logInfo)) {
                foreach ($logInfo as $k => $v) {
                    $logInfo[$k]['head_portrait'] = imgUrl($v['head_portrait']);
                    $logInfo[$k]['price'] = priceFormat($v['price']);
                }
            }
            # 查询红包信息
            $redpacketInfo = Db::table('redpacket r')
                ->field('name,head_portrait,pack_type,pack_num,pack_title,plurs_num')
                ->leftJoin('member m', 'm.code=r.member_code')
                ->where(array('r.id' => $redpacketId))
                ->find();
            if (!empty($redpacketInfo)) {
                $redpacketInfo['head_portrait'] = imgUrl($redpacketInfo['head_portrait']);
            }
            return array('status' => true, 'msg' => '查询成功', 'logInfo' => $logInfo, 'redPacketInfo' => $redpacketInfo);
        } else {
            return array('status' => false, 'msg' => '红包ID为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 红包发送记录
     */
    function logSend()
    {
        $info = Db::table('redpacket')
            ->where(array('member_code' => $this->code))
            ->order(array('id' => 'desc'))
            ->select();
        return array('status' => true, 'msg' => '查询成功', 'info' => $info);
    }
}